package com.ytjj.qmyx.mall.utils;

import com.ytjj.common.api.ResultCode;
import com.ytjj.common.exception.ApiException;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 *
 *  *
 **/
public class MD5Utils {

    /**
     * 获取签名
     *
     * @param data 请求参数
     * @param key 密钥
     * @return
     */
    public static String generateSignature(Map<String, Object> data, String key) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (Object k : keyArray) {
            String v = data.get(k)+"";
            sb.append(k).append(v.trim());
        }
        sb.append(key);
        try {
            return MD5(sb.toString()).toUpperCase();
        } catch (Exception e) {
            throw new ApiException(ResultCode.FAILED);
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
}
